# -*- coding: utf-8 -*-
import collections
from pathlib import Path
import json
from datetime import datetime, timedelta
import gc
import os
import time
from django.db.models import Sum, Count
from django.http import HttpResponse, JsonResponse
from django.http import StreamingHttpResponse
from django.shortcuts import render, redirect
from django.views.decorators import gzip
from django.conf import settings
from app01 import models, form
from utils import utils


def init(request):
    init_user = {
        "user_name": "admin",
        "pwd": "1fb0f3513b4171cecd04216dee37638d",
        "nick_name": "超级管理员",
        "auth_level": 1,
    }
    manage_obj = models.ManagerList.objects
    if not manage_obj.filter(user_name="admin").first():
        manage_obj.create(**init_user)
    return redirect('/login.html/')


def init_items(request):
    item_list = [
        {
            "item_name": "龚庭·排毒膏",
            "item_image": "/img/pdg.png",
            "item_introduction": "排出鼻腔清脓鼻涕等鼻毒，每天使用一次，将鼻腔清理干净。",
            "item_price": 138,
        },
        {
            "item_name": "龚庭·修复膏",
            "item_image": "/img/xfg.png",
            "item_introduction": "快速缓解鼻部问题，修复肿大鼻甲、粘膜等急慢性鼻腔损伤，每天早中晚各使用一次。",
            "item_price": 598,
        },
        {
            "item_name": "龚庭·巩固膏",
            "item_image": "/img/ggg.png",
            "item_introduction": "加强巩固疗效，拒绝顽固鼻患再燃及复发，每天睡前使用一次",
            "item_price": 388,
        },
    ]
    item_obj_list = []
    for each in item_list:
        item_obj_list.append(models.ItemPriceList(**each))

    models.ItemPriceList.objects.bulk_create(item_obj_list)
    return redirect('/admin/manage_item_price.html/')


def admin(request):
    return render(request, "admin.html/")


def admin_accounts(request):
    accounts_obj = models.ManagerList.objects.all()

    return render(request, "admin_accounts.html/", {"accounts_obj": accounts_obj})


def accounts_add(request):
    if request.method == "GET":
        form_add = form.ManagerForm()

        return render(request, 'accounts_add.html', {"form_add": form_add})

    form_add = form.ManagerForm(data=request.POST)

    if form_add.is_valid():
        new_username = form_add.cleaned_data['user_name']
        username_obj = models.ManagerList.objects.filter(user_name=new_username).first()
        if username_obj:
            form_add.add_error("user_name", "用户名已存在！")
            return render(request, 'accounts_add.html', {"form_add": form_add})
        else:
            form_add.save()

            return redirect('/admin/accounts.html/')

    else:

        return render(request, 'accounts_add.html', {"form_add": form_add})


def accounts_edit(request, uid):
    accounts_obj = models.ManagerList.objects.filter(id=uid).first()
    old_username = accounts_obj.user_name
    if request.method == "GET":
        form_add = form.ManagerEditForm(instance=accounts_obj)

        return render(request, 'accounts_edit.html', {"form_add": form_add})

    form_add = form.ManagerEditForm(data=request.POST, instance=accounts_obj)

    if form_add.is_valid():
        new_username = form_add.cleaned_data['user_name']

        username_obj = models.ManagerList.objects.filter(user_name=new_username).exclude(user_name=old_username).first()

        if username_obj:
            form_add.add_error("user_name", "用户名已存在！")
            return render(request, 'accounts_edit.html', {"form_add": form_add})
        else:
            form_add.instance.pwd = utils.md5(form_add.cleaned_data['pwd'])
            form_add.save()

            return redirect('/admin/accounts.html/')

    else:

        return render(request, 'accounts_edit.html', {"form_add": form_add})


def accounts_del(request):
    uid = request.POST.get("uid")
    models.ManagerList.objects.filter(id=uid).delete()

    return JsonResponse({"ret": True}, safe=True)


def manage_item_price(request):
    item_obj = models.ItemPriceList.objects.all()

    return render(request, "manage_item_price.html/", {"item_obj": item_obj})


def item_add(request):
    if request.method == "GET":
        form_add = form.ItemPriceListForm()

        return render(request, 'item_add.html', {"form_add": form_add})

    form_add = form.ItemPriceListForm(request.POST, request.FILES)

    if form_add.is_valid():

        form_add.save()

        return redirect('/admin/manage_item_price.html/')

    else:

        return render(request, 'item_add.html', {"form_add": form_add})


def item_edit(request, iid):
    item_price_obj = models.ItemPriceList.objects.filter(item_id=iid).first()
    if request.method == "GET":
        form_add = form.ItemPriceListForm(instance=item_price_obj)

        return render(request, 'item_edit.html', {"form_add": form_add})

    form_add = form.ItemPriceListForm(request.POST, request.FILES, instance=item_price_obj, )

    if form_add.is_valid():

        form_add.save()

        return redirect('/admin/manage_item_price.html/')

    else:

        return render(request, 'item_edit.html', {"form_add": form_add})


def item_del(request):
    iid = request.POST.get("iid")
    models.ItemPriceList.objects.filter(item_id=iid).delete()

    return JsonResponse({"ret": True}, safe=True)


# 客户管理列表
def admin_customer_list(request):
    customer_list = models.CustomerInfo.objects.all()

    return render(request, 'customer_manage.html/', {"customer_list": customer_list})


def customer_del(request):
    pid = request.POST.get("pid")
    pid_obj = models.CustomerInfo.objects.filter(pid=pid).first()
    test_obj = models.TestList.objects.filter(pid=pid_obj)
    models.ReturningVisits.objects.filter(pid=pid_obj).all().delete()
    for test_object in test_obj.all():
        img_obj = models.ImList.objects.filter(test_id=test_object)
        tid_obj = test_object.tid
        if tid_obj:
            tid_obj.delete()
        im_to_del = list(img_obj.values('im_path'))

        if im_to_del:
            im_to_del = [Path(a['im_path']) for a in im_to_del]

            im_to_del = [Path(os.path.join(settings.BASE_DIR, 'test_images', paths)) for paths in im_to_del]
            for im_file in im_to_del:
                try:
                    os.remove(im_file)
                except FileNotFoundError as e:
                    pass
        img_obj.delete()
        models.WorkingList.objects.filter(test_id=test_object).delete()
    test_obj.all().delete()
    pid_obj.delete()
    return JsonResponse({"ret": True})

# 登录
def login(request):
    if request.method == "GET":
        remember = request.session.get("remember", 0)

        if remember:
            user_name = request.session.get("name")
            login_form = form.ManagerListForm({"user_name": user_name})
        else:
            login_form = form.ManagerListForm()
        return render(request, 'login.html/', {"login_form": login_form})
    login_form = form.ManagerListForm(data=request.POST)

    if login_form.is_valid():

        remember = login_form.cleaned_data.get("remember")
        if remember:
            login_form.cleaned_data.get("remember")
            request.session["remember"] = remember

            request.session["name"] = login_form.cleaned_data.get("user_name")
        login_form.cleaned_data.pop("remember")
        login_result = models.ManagerList.objects.filter(**login_form.cleaned_data).first()
        if not login_result:
            login_form.add_error("pwd", "用户名或密码错误！")
            return render(request, 'login.html/', {"login_form": login_form})
        request.session["info"] = {"id": login_result.id, "name": login_result.user_name,
                                   "auth_level": login_result.auth_level}

        return redirect("/home.html/")

    return render(request, 'login.html/', {"login_form": login_form})


def logout(request):
    request.session.pop("info")
    return redirect("/login.html/")


def edit_username(request):
    user_obj = request.tracer
    if request.method == "GET":
        form_edit = form.EditUserForm({"user_name": user_obj.user_name})

        return render(request, 'edit_username.html', {"form_edit": form_edit, "old_user_name": user_obj.user_name})

    form_edit = form.EditUserForm(data=request.POST, instance=user_obj)

    if form_edit.is_valid():

        if user_obj.pwd == form_edit.cleaned_data["pwd"]:
            form_edit.instance.pwd = utils.md5(form_edit.cleaned_data["new_pwd"])

            form_edit.save()

            return logout(request)

        else:
            form_edit.add_error("pwd", "原密码输入错误！")
            return render(request, 'edit_username.html', {"form_edit": form_edit, "old_user_name": user_obj.user_name})
    else:

        return render(request, 'edit_username.html', {"form_edit": form_edit, "old_user_name": user_obj.user_name})


def check_user_name(request):
    status = models.ManagerList.objects.filter(user_name=request.POST.get("user_name")).exclude(
        user_name=request.POST.get("old_user_name")).first()
    if status:
        ret = True
    else:
        ret = False
    return JsonResponse({"ret": ret}, safe=False)


def edit_nickname(request):
    user_obj = request.tracer
    if request.method == "GET":
        form_edit = form.EditNickname()

        return render(request, 'edit_nickname.html', {"form_edit": form_edit, })

    form_edit = form.EditNickname(data=request.POST, instance=user_obj)

    if form_edit.is_valid():

        form_edit.save()

        return redirect("/customer_list.html/")


    else:

        return render(request, 'edit_nickname.html', {"form_edit": form_edit, })


# 主页
def home(request):
    epigram = utils.sayings()
    return render(request, 'home.html/', {"epigram": epigram})


# 客户列表
def customer_list(request):
    customer_list = models.CustomerInfo.objects.all()

    return render(request, 'customer_list.html/', {"customer_list": customer_list})


# 客户个人信息

def customer_details(request, pid):
    result = models.CustomerInfo.objects.filter(pid=pid).first()

    result_test_list = models.TestList.objects.filter(pid=pid).all().order_by("-test_date")

    result_buying_list = models.BuyingList.objects.filter(pid=pid).all().order_by("-buying_date")
    request.session["cus_info"] = {
        "pid": pid,
        "name": result.name
    }
    request.pathtools.path_infos[f"/customer/{pid}/details.html/"] = result.name
    return render(request, 'customer_details.html/', {
        "result": result,
        "result_test_list": result_test_list,
        "result_buying_list": result_buying_list,
    })


def search_customer(request):
    if request.method == "POST":
        try:
            pid = request.POST.get('name_searched')

            return customer_details(request, pid)
        except Exception as e:
            request.authtools.error = "错误，无此客户信息！"
            return redirect("/error.html/")


def show_customer(request):
    if request.method == "POST":
        name = request.POST.get('name')

        result = list(
            models.CustomerInfo.objects.filter(name__icontains=name).values('pid', 'name', 'sex', 'age', 'phone'))

        ajax_dict = {
            "customers_found": result
        }
        return JsonResponse(ajax_dict, safe=False)


def customer_edit(request, pid):
    result = models.CustomerInfo.objects.filter(pid=pid).first()

    if request.method == "GET":
        form_edit = form.CustomerForm(instance=result)

        return render(request, 'customer_edit.html', {"form_edit": form_edit})

    form_edit = form.CustomerForm(data=request.POST, instance=result)

    if form_edit.is_valid():
        form_edit.save()

        return redirect('/customer_list.html/')

    else:

        return render(request, 'customer_edit.html', {"form_edit": form_edit})


def customer_add(request):
    customer_idx = models.CustomerInfo.objects.aggregate(customer_idx=Count("pid"))
    customer_idx = customer_idx["customer_idx"] + 1
    if request.method == "GET":
        form_add = form.CustomerForm()

        return render(request, 'customer_add.html', {"form_add": form_add, "customer_idx": customer_idx})

    form_add = form.CustomerForm(data=request.POST)

    if form_add.is_valid():
        form_add.save()

        result = models.CustomerInfo.objects.last()
        description = f"添加用户【{result.name}】"
        utils.record_working(request.tracer, {"pid": result}, 1, description)
        return redirect(f'/customer/{result.pid}/details.html/')

    else:

        return render(request, 'customer_add.html', {"form_add": form_add, "customer_idx": customer_idx})


def test_add(request, pid):
    if request.method == "GET":
        trail_or_bought = models.CustomerInfo.objects.filter(pid=pid).first().trail_or_bought
        form_add = form.TestForm({
            "pid": pid,
            "test_date": utils.today_date(),
            "trail_or_bought": trail_or_bought,
        })

        return render(request, 'test_add.html', {"form_add": form_add, "pid": pid})

    form_add = form.TestForm(data=request.POST)

    if form_add.is_valid():
        form_add.save()
        last_test_date = form_add.cleaned_data.get('test_date')
        models.CustomerInfo.objects.filter(pid=pid).update(last_test_date=last_test_date)
        result = models.TestList.objects.last()
        description = f"添加服务【{result.test_id}】"
        utils.record_working(request.tracer, {"test_id": result}, 2, description)
        return redirect(f'/customer/{pid}/details.html/')

    else:

        return render(request, 'test_add.html', {"form_add": form_add, "pid": pid})


def test_del(request):
    test_id = request.POST.get('test_id')
    test_obj = models.TestList.objects.filter(test_id=test_id)

    test_object = test_obj.first()
    tid_obj = test_object.tid
    tid_obj.delete()
    img_obj = models.ImList.objects.filter(test_id=test_object)
    im_to_del = list(img_obj.values('im_path'))

    if im_to_del:
        im_to_del = [Path(a['im_path']) for a in im_to_del]

        im_to_del = [Path(os.path.join(settings.BASE_DIR, 'test_images', paths)) for paths in im_to_del]
        for im_file in im_to_del:
            os.remove(im_file)
    img_obj.delete()
    models.WorkingList.objects.filter(test_id=test_object).delete()
    test_obj.delete()

    return JsonResponse({"ret": True})


def test_edit(request, test_id):
    result = models.TestList.objects.filter(test_id=test_id).first()

    if request.method == "GET":
        test_edit = form.TestForm(instance=result)

        return render(request, 'test_edit.html', {"test_edit": test_edit, "pid": result.pid.pid})

    test_edit = form.TestForm(data=request.POST, instance=result)

    if test_edit.is_valid():
        test_edit.save()

        return redirect(f'/customer/{result.pid.pid}/details.html/')

    else:

        return render(request, 'test_edit.html', {"test_edit": test_edit, "pid": result.pid.pid})


def buying_add(request, pid):
    '''添加购买记录'''
    operator_obj = request.tracer
    price_obj = models.ItemPriceList.objects.all()
    user_obj = models.CustomerInfo.objects.filter(pid=pid).first()
    buying_date = utils.today_date()

    if request.method == "GET":
        form_add = form.BuyingForm()

        return render(request, 'buying_add_new.html',
                      {"form_add": form_add, "pid": pid, "price_obj": price_obj, "user_obj": user_obj,
                       "operator_obj": operator_obj,
                       "buying_date": buying_date})

    form_add = form.BuyingForm(data=request.POST)
    item_id_list = request.POST.get('item_id_list')
    item_id_list = json.loads(item_id_list)

    if form_add.is_valid():

        order_id = datetime.now().strftime('%Y%m%d%H%M%S%f')[:-3]
        form_add.instance.order_id = order_id
        form_add.save()
        test_obj = models.TestList.objects.filter(test_date__date=datetime.now().strftime("%Y-%m-%d"))
        pay_or_not = form_add.cleaned_data.get('bill_status')
        if not test_obj.last():
            test_dic = {
                "test_date": buying_date,
                "trail_or_bought": 2,
                "pid": user_obj,
            }
            if not pay_or_not == 1:
                test_dic["trail_or_bought"] = 1

            models.TestList.objects.create(**test_dic)
        else:
            if pay_or_not == 1:
                test_obj.update(trail_or_bought=2)
            else:
                test_obj.update(trail_or_bought=1)
        order_id_obj = models.BuyingList.objects.last()
        order_list = [models.OrderList(item_id=models.ItemPriceList.objects.filter(item_id=item_id).first(),
                                       order_id=order_id_obj, order_quantity=order_quantity)
                      for item_id, order_quantity in item_id_list.items()]
        models.OrderList.objects.bulk_create(order_list)

        if form_add.cleaned_data.get('bill_status') == 1:
            models.CustomerInfo.objects.filter(pid=pid).update(trail_or_bought=2)
        buying_obj = models.BuyingList.objects.last()
        buying_id = buying_obj.buying_id
        description = f"完成订单【{buying_id}】"
        utils.record_working(request.tracer, {"buying_id": buying_obj}, 5, description)

        return redirect(f'/buying/{buying_id}/check.html/')

    else:

        return render(request, 'buying_add_new.html',
                      {"form_add": form_add, "pid": pid, "price_obj": price_obj, "user_obj": user_obj,
                       "operator_obj": operator_obj,
                       "buying_date": buying_date})


def buying_edit(request, buying_id):
    result = request.authtools
    bill_obj = models.OrderList.objects.filter(order_id=result).all()

    if request.method == "GET":
        form_edit = form.BuyingEditForm(instance=result)

        return render(request, 'buying_edit.html',
                      {"form_edit": form_edit, "pid": result.pid.pid,
                       "bill_obj": bill_obj,
                       "result": result,
                       })

    form_edit = form.BuyingEditForm(data=request.POST, instance=result)

    if form_edit.is_valid():
        pay_or_not = form_edit.cleaned_data.get('bill_status')
        form_edit.save()
        test_obj = models.TestList.objects.filter(test_date__date=result.buying_date.date())
        if pay_or_not == 1:
            test_obj.update(trail_or_bought=2)
        else:
            test_obj.update(trail_or_bought=1)
        return redirect(f'/customer/{result.pid.pid}/details.html/')

    else:

        return render(request, 'buying_edit.html',
                      {"form_edit": form_edit, "pid": result.pid.pid, "bill_obj": bill_obj
                       })


def buying_check(request, buying_id):
    result = models.BuyingList.objects.filter(buying_id=buying_id).first()
    bill_obj = models.OrderList.objects.filter(order_id=result).all()

    return render(request, 'buying_check.html',
                  {"pid": result.pid.pid,
                   "bill_obj": bill_obj,
                   "result": result,
                   })


@gzip.gzip_page
def video_cap(request, lt, st):
    global cam
    cam = utils.VideoCamera()

    cam_gen = utils.gen(cam, lt, st)

    return StreamingHttpResponse(cam_gen, content_type="multipart/x-mixed-replace;boundary=frame")


def release_cap(request, pid):
    global cam
    del cam
    gc.collect()
    return redirect(f"/customer/{pid}/details.html/")


def image_cap(request):
    global cam
    test_id = int(request.POST.get('test_id'))
    lt = int(request.POST.get('lt'))
    st = int(request.POST.get('st'))
    cam.get_frame(lt=lt, st=st)

    test_id_obj = models.TestList.objects.get(test_id=test_id)
    pid = test_id_obj.pid.pid
    name = test_id_obj.pid.name

    date_ = time.strftime("%Y%m%d", time.localtime())
    time_ = time.strftime("%H%M%S", time.localtime())
    save_dir = os.path.join(settings.BASE_DIR, f'test_images\\{pid}_{name}')
    if not os.path.exists(save_dir):
        os.mkdir(save_dir)
    file_dir = os.path.join(save_dir, f'{date_}')
    if not os.path.exists(file_dir):
        os.mkdir(file_dir)
    image_path = f'{pid}_{name}\\{date_}\\{time_}_{utils.random_file_name()}.png'

    cam.cap_image().save(os.path.join(settings.BASE_DIR, f'test_images\\{image_path}'))

    data_save = {"test_id": test_id, "im_path": image_path}

    models.ImList.objects.create(im_path=image_path, test_id=test_id_obj)

    return JsonResponse(data_save, safe=False)


def save_and_del_img(request):
    try:
        img_list_get = json.loads(request.POST.get("img_to_save"))
        test_id = request.POST.get("test_id")

        img_list_sql = [path_.replace("/image/", '') for path_ in img_list_get]

        im_obj = models.ImList.objects.filter(test_id=test_id).exclude(im_path__in=img_list_sql)
        im_to_del = list(im_obj.values('im_path'))

        if im_to_del:
            im_to_del = [Path(a['im_path']) for a in im_to_del]

            im_to_del = [Path(os.path.join(settings.BASE_DIR, 'test_images', paths)) for paths in im_to_del]
            if img_list_get:
                dir_path = os.path.dirname(Path(settings.BASE_DIR + img_list_get[0].replace("image", 'test_images')))
            else:
                dir_path = os.path.join(settings.BASE_DIR, 'test_images')
            dir_path = Path(dir_path)

            for root, ds, fs in os.walk(dir_path):
                for f in fs:

                    fullname = os.path.join(root, f)
                    if Path(fullname) in im_to_del:
                        os.remove(fullname)

            im_obj.delete()


    except Exception as e:
        return JsonResponse({"ret": False, 'msg': f"{e}"})

    return JsonResponse({"ret": True, })


def camera_test_add(request, pid):
    now_ = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    pid_obj = models.CustomerInfo.objects.filter(pid=pid).first()
    trail_or_bought = pid_obj.trail_or_bought
    test_id = models.TestList.objects.create(
        pid=pid_obj,
        test_date=now_,
        trail_or_bought=trail_or_bought,
    ).test_id

    return redirect(f"/camera/{test_id}/test.html")


def camera_test(request, test_id):
    result = models.TestList.objects.filter(test_id=test_id).first()
    if request.method == "GET":
        return render(request, 'camera_cap.html',
                      {"test_id": test_id, "result": result})


def test_report(request):
    global cam
    del cam

    gc.collect()

    test_id = request.POST.get("test_id")

    image_paths = request.POST.get("image_paths").strip().split()

    test_obj = models.TestList.objects.filter(test_id=test_id)
    test_value = test_obj.values().first().update(
        {"test_result": test_obj.first().tid.test_result if test_obj.first().tid else ""})
    form_add = form.TestImgForm(instance=test_obj.first(), data=test_value)

    result = {"test_id": test_id, "test_obj": test_obj.first(), "image_paths": image_paths, "form_add": form_add}

    return render(request, 'test_report.html', {"result": result})


def test_report_edit(request, test_id):
    image_paths = models.ImList.objects.filter(test_id=test_id).values("im_path")

    test_obj = models.TestList.objects.filter(test_id=test_id)
    test_value = test_obj.values().first().update(
        {"test_result": test_obj.first().tid.test_result if test_obj.first().tid else ""})
    if request.method == "GET":
        form_add = form.TestImgForm(instance=test_obj.first(), data=test_value)

        result = {"test_id": test_id, "test_obj": test_obj.first(), "image_paths": image_paths, "form_add": form_add}

        return render(request, 'test_report.html', {"result": result})

    form_add = form.TestImgForm(instance=test_obj.first(), data=request.POST)
    if form_add.is_valid():

        form_add.save()

        return redirect(f'/customer/{test_obj.first().pid.pid}/details.html/')

    else:
        result = {"test_id": test_id, "test_obj": test_obj.first(), "image_paths": image_paths, "form_add": form_add}
        return render(request, 'test_report.html', {"result": result})


def save_test_report(request):
    tid = request.POST.get("tid")

    test_result = request.POST.get("test_result")
    test_reporter = request.POST.get("test_reporter")

    manager_obj = models.ManagerList.objects.filter(id=int(test_reporter)).first()
    if tid:

        tid = models.TestReport.objects.filter(tid=tid)
        tid.update(test_result=test_result, reporter=manager_obj)
        tid = tid.first()
        working_kind = 4
        add_element = False
        description = f"更新鼻道镜报告"
    else:
        tid = models.TestReport.objects.create(test_result=test_result, reporter=manager_obj, )
        working_kind = 3
        add_element = True
        description = f"生成鼻道镜报告"

    utils.record_working(request.tracer, {"tid": tid}, working_kind, description)
    return JsonResponse({"tid": tid.tid, "add_element": add_element}, safe=False)


def refresh_trail_counts(request):
    pid = int(request.POST.get("pid"))
    former_trail_counts = models.CustomerInfo.objects.filter(pid=pid).values("trial_counts").first().get("trial_counts")
    trail_counts = models.TestList.objects.filter(pid=pid, trail_or_bought=1).aggregate(
        trail_counts=Count('trail_or_bought')).get("trail_counts")

    if trail_counts != former_trail_counts:
        models.CustomerInfo.objects.filter(pid=pid).update(trial_counts=trail_counts)

    total_pay = models.BuyingList.objects.filter(pid=pid).aggregate(total_pay=Sum('total_amount')).get("total_pay")
    total_pay = total_pay if total_pay else 0

    result = {"trail_counts": trail_counts, "total_pay": total_pay}
    return JsonResponse(result, safe=False)


def error_page(request):
    return render(request, "error.html", {"error": request.authtools.error})


def chart(request):
    """可视化统计"""

    return render(request, "chart.html")


def chart_test_p_day(request):
    today = datetime.now().date()
    date_dict = collections.OrderedDict()
    date_dict_buying = collections.OrderedDict()
    for i in range(0, 31):
        date_ = today - timedelta(days=i)
        date_dict[date_.strftime("%Y-%m-%d")] = [time.mktime(date_.timetuple()) * 1000, 0]
        date_dict_buying[date_.strftime("%Y-%m-%d")] = [time.mktime(date_.timetuple()) * 1000, 0]

    result = models.TestList.objects.filter(test_date__gte=today - timedelta(days=30)).extra(
        select={'ctime': "DATE_FORMAT(test_list.test_date, '%%Y-%%m-%%d')"}
    ).values('ctime').annotate(ct=Count('test_id'))
    result_buying = models.BuyingList.objects.filter(buying_date__gte=today - timedelta(days=30)).extra(
        select={'ctime': "DATE_FORMAT(buying_list.buying_date, '%%Y-%%m-%%d')"}
    ).values('ctime').annotate(ct=Count('buying_id'))

    for item in result:
        date_dict[item['ctime']][1] = item['ct']
    data_list = list(date_dict.values())
    for b_item in result_buying:
        date_dict_buying[b_item['ctime']][1] = b_item['ct']
    data_list_buying = list(date_dict_buying.values())
    return JsonResponse({'status': True, 'data': {
        "data_list": data_list,
        "data_list_buying": data_list_buying,
    }})


def chart_total_amount_p_c(request):
    result = models.BuyingList.objects.filter(bill_status=1).values_list('pid__name').annotate(
        tm=Sum('total_amount')).order_by('-tm')

    total_count = models.TestList.objects.values_list('pid__name').annotate(
        tc=Count('test_id')).order_by('-tc')
    trail = models.TestList.objects.filter(trail_or_bought=1).values_list('pid__name').annotate(
        tt=Count('test_id'))
    test_result = collections.OrderedDict()

    for each in total_count:
        test_result[each[0]] = {
            "total": each[1],
            "trail": 0,
            "bought": 0,
        }
    for k, v in test_result.items():
        for e in trail:
            if e[0] == k:
                v["trail"] = e[1]
                v["bought"] = v["total"] - e[1]
                break
            else:
                v["bought"] = v["total"]
    category = list(test_result.keys())
    series = []
    data = collections.OrderedDict()
    choice = (
        ("bought", "已购买"),
        ("trail", "试用"),

    )

    for z in choice:
        data[z[0]] = {"name": z[1],
                      "data": [],

                      }

        series.append(data)
    date_k = data.keys()
    for y in test_result.values():
        for k_, v_ in y.items():
            if k_ in date_k:
                data[k_]["data"].append(v_)

    series = list(data.values())

    return JsonResponse({
        "result": list(result),
        "category": category,
        "series": series,

    })


# 回访
def returning_visits_list(request, pid):
    rv_list = models.ReturningVisits.objects.filter(pid__pid=pid).order_by("-rid")
    customer_obj = models.CustomerInfo.objects.filter(pid=pid).first()

    return render(request, 'rv_list.html/', {
        "rv_list": rv_list,
        "pid": pid,
        "customer_obj": customer_obj,
    })


def returning_visits_add(request, pid):
    customer_obj = models.CustomerInfo.objects.filter(pid=pid).first()
    test_obj = models.TestList.objects.filter(pid__pid=pid).last()
    rv_obj = models.ReturningVisits.objects.filter(pid__pid=pid).last()
    if request.method == "GET":
        form_add = form.ReturningVisitsForm(
            data={'pid': customer_obj, "create_time": datetime.now().strftime("%Y-%m-%d %H:%M")})

        return render(request, 'rv_add.html', {
            "form_add": form_add,
            "customer_obj": customer_obj,
            "test_obj": test_obj,
            "rv_obj": rv_obj,
        })

    form_add = form.ReturningVisitsForm(data=request.POST, )

    if form_add.is_valid():
        last_r_v_date = form_add.cleaned_data.get("create_time")
        models.CustomerInfo.objects.filter(pid=pid).update(returning_visits_date=last_r_v_date)
        form_add.save()
        result = models.ReturningVisits.objects.last()
        description = f"添加回访【{result.rid}】"
        utils.record_working(request.tracer, {"rid": result}, 6, description)
        return redirect(f'/returning_visits/{pid}/list.html/')

    else:

        return render(request, 'rv_add.html', {
            "form_add": form_add,
            "customer_obj": customer_obj,
            "test_obj": test_obj,
            "rv_obj": rv_obj,
        })


def returning_visits_edit(request, rid):
    rv_obj = models.ReturningVisits.objects.filter(rid=rid).first()

    customer_obj = rv_obj.pid
    test_obj = models.TestList.objects.filter(pid__pid=rv_obj.pid.pid).last()
    if request.method == "GET":
        form_add = form.ReturningVisitsForm(instance=rv_obj)

        return render(request, 'rv_edit.html', {
            "form_add": form_add,
            "customer_obj": customer_obj,
            "test_obj": test_obj,
            "rv_obj": rv_obj,
        })

    form_add = form.ReturningVisitsForm(data=request.POST, instance=rv_obj)

    if form_add.is_valid():

        form_add.save()

        return redirect(f'/returning_visits/{rv_obj.pid.pid}/list.html/')

    else:

        return render(request, 'rv_edit.html', {
            "form_add": form_add,
            "customer_obj": customer_obj,
            "test_obj": test_obj,
            "rv_obj": rv_obj,
        })


def show_info(request, ):
    test_kinds = {
        'test_result': '检查报告',
        'feedback': '客户反馈',
    }
    order_kinds = {
        'order': '购买信息'
    }
    info = request.POST.get('info').split('-')
    info_kind = info[0]
    id_kind = info[1]
    kid = int(info[2])
    result = {"result": ""}
    if info_kind in test_kinds.keys():
        result = models.TestList.objects.filter(**{id_kind: kid}).values(info_kind).first()
        if result[info_kind]:
            result = {"result": (test_kinds[info_kind], result[info_kind])}
    elif info_kind in order_kinds.keys():
        test_obj = models.TestList.objects.filter(**{id_kind: kid}).first()
        buying_obj = models.BuyingList.objects.filter(pid=test_obj.pid,
                                                      buying_date__date=test_obj.test_date.date()).first()
        if buying_obj:
            order_obj = models.OrderList.objects.filter(order_id=buying_obj).all()
            order_content = ''
            bill_status = list((a[1] for a in models.BuyingList.status if buying_obj.bill_status == a[0]))[0]

            for each in order_obj:
                order_content += f"{each.item_id.item_name}×{each.order_quantity} "
            order_result = f"<br>购买时间：{buying_obj.buying_date}<br>订单明细：{order_content}<br>订单金额：{buying_obj.total_amount}元（{bill_status}）"
            result = {"result": (order_kinds[info_kind], order_result)}

    return JsonResponse(result, safe=False)


def test_report_model(request):
    with open('.\\utils\\tests_report_model.txt', 'r', encoding="utf-8") as f:
        model = f.read()

    result = {"model": model}
    return JsonResponse(result, safe=False)
